<?php

namespace app\xwam\controller;

/**
 * Description of LoginController
 *
 * @since 1.0 <2015-10-20> SoChishun <14507247@qq.com> Added.
 */
class LoginController extends \think\Controller {
    /**
     *
     * @var string
     */
    protected $loginErrorCountId='login_error_count';
    public function index() {
        //$m_site = new \app\xwam\model\XwamConfModel();
        //$data = $m_site->findSite(1, 'admin');
        $data = [];
        $int_loginErrorCount = \think\Session::get($this->loginErrorCountId);
        $showCaptcha = !is_null($int_loginErrorCount);
        return view('', ['site' => $data, 'showCaptcha' => $showCaptcha]);
    }

    public function doLogin($login_name = '', $password = '', $captcha = '') {
        $intLoginErrorCount = \think\Session::get($this->loginErrorCountId);
        if(is_null($intLoginErrorCount)){
            $intLoginErrorCount=0;
        }
        if ($intLoginErrorCount > 5) {
            exit('您已经出错5次, 请5分钟后再登录!');
        }
        if (!isset($_POST['captcha'])) {
            $captcha = null;
        }
        if (!$login_name || !$password || (!is_null($captcha) && !$captcha)) {
            \think\Session::set($this->loginErrorCountId, $intLoginErrorCount + 1);
            $this->error('表单填写不完整!', url('index'), '', 2);
        }
        $mLogin = new \app\xwam\model\LoginModel();
        $result = $mLogin->login($login_name, $password, $captcha, $msg);
        if ($result) {
            // read site_info
            $m_site = new \app\xwam\model\XwamConfModel();
            $data = $m_site->findSite(1, $msg['user_name'], false);
            if (!$data) {
                exit('未开通CRM功能!');
            }
            // 保存登录信息到会话中
            \think\Session::delete($this->loginErrorCountId);
            \think\Session::set('site_conf', $data);
            $this->redirect('index/index');
        } else {
            \think\Session::set($this->loginErrorCountId, $intLoginErrorCount + 1);
            $this->error(xsfn_message_format($msg), url('index'), '', 2);
        }
    }

    public function logout() {
        \app\xwam\model\LoginModel::logout();
        header('location:' . url('Login/index'));
    }

}
